package com.qdh;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

public class DataFlowJob {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        // 1. 初始化配置
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hadoop10:8020");
        //2. 创建job
        Job job = Job.getInstance(conf);
        job.setJarByClass(DataFlowJob.class);

        //3. 设置输入格式化工具和输出格式化
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        //4. 设置输入路径和输出路径
/*        TextInputFormat.addInputPath(job,new Path("/mapreduce/demo2/phone.log"));
        TextOutputFormat.setOutputPath(job,new Path("/mapreduce/demo2/out5"));*/
        TextInputFormat.addInputPath(job,new Path(args[0]));
        TextOutputFormat.setOutputPath(job,new Path(args[1]));


        //5. 设置mapper和reducer
        job.setMapperClass(DataFlowMapper.class);
        job.setReducerClass(DataFlowReducer.class);

        // 6. 设置mapper的kv类型和reducer的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(DataFlowWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        // 7. 启动job
        boolean b = job.waitForCompletion(true);
        System.out.println(b?"成功":"失败");
    }


    //局部计算
    static class DataFlowMapper extends Mapper<LongWritable, Text, Text, DataFlowWritable> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] split = value.toString().split("\t");

            context.write(new Text(split[1]),
                    new DataFlowWritable(
                            Integer.parseInt(split[6]),
                            Integer.parseInt(split[7])
                    ));
        }
    }
    //全局计算
    static class DataFlowReducer extends Reducer<Text, DataFlowWritable, Text, Text> {
        @Override
        protected void reduce(Text key, Iterable<DataFlowWritable> values,Context context) throws IOException, InterruptedException {
            int upsum = 0;
            int downsum = 0;

            for (DataFlowWritable value : values) {
               upsum += value.getUp();
               downsum += value.getDown();
            }
            context.write(key,new Text("上传流量:"+upsum+"  下载流量:"+downsum+"  总数据流量:  "+(upsum+downsum)));

        }
    }


}
